﻿using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Timers;
using SXL.Authentication;

namespace MyOTP2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        System.Timers.Timer timer;


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            OTPItemsSource = new ObservableCollection<AuthInfoViewModel>();
            try
            {
                LoadData();
            }
            catch (Exception ex)
            {

            }

            InitTimer();
        }


        public void InitTimer()
        {
            timer = new System.Timers.Timer();
            timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {

            List<AuthInfoViewModel> updateList = new List<AuthInfoViewModel>();
            System.Windows.Application.Current.Dispatcher.Invoke(() =>
            {
                updateList = OTPItemsSource.ToList();
            });
            foreach (var item in updateList)
            {
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    item.UpdateCode();
                });
            }
        }

        public ObservableCollection<AuthInfoViewModel> OTPItemsSource
        {
            get { return (ObservableCollection<AuthInfoViewModel>)GetValue(OTPItemsSourceProperty); }
            set { SetValue(OTPItemsSourceProperty, value); }
        }

        // Using a DependencyProperty as the backing store for OTPItemsSource.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty OTPItemsSourceProperty =
            DependencyProperty.Register("OTPItemsSource", typeof(ObservableCollection<AuthInfoViewModel>), typeof(MainWindow), new PropertyMetadata(new ObservableCollection<AuthInfoViewModel>()));


        string UserInfoSavePath = "userInfo.json";

        public void LoadData()
        {
            OTPItemsSource = new ObservableCollection<AuthInfoViewModel>();
            if (!File.Exists(UserInfoSavePath))
            {
                return;
            }

            var dataStr = File.ReadAllText(UserInfoSavePath, Encoding.UTF8);
            if (!string.IsNullOrEmpty(dataStr))
            {
                var otpUserList = JsonConvert.DeserializeObject<List<AuthInfoModel>>(dataStr);

                var otpUserViewList = otpUserList.Select(x => new AuthInfoViewModel
                {
                    UserInfo = x,
                    TagName = x.TagName,
                    OTPKey = x.OTPKey,
                    UserRealName = x.UserRealName,
                    UserName = x.UserName,
                    Password = x.Password,
                });
                OTPItemsSource = new ObservableCollection<AuthInfoViewModel>(otpUserViewList);
            }
            else
            {
                OTPItemsSource = new ObservableCollection<AuthInfoViewModel>();
            }
        }


        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            SaveData();
            HuataiCloud.Dispose();
            //ChromeWebTool.WebDriverHelper.Dispose();
        }
        public void SaveData()
        {
            OTPItemsSource.ToList().ForEach(t =>
            {
                t.UserInfo = new AuthInfoModel();
                t.UserInfo.UserRealName = t.UserRealName;
                t.UserInfo.TagName = t.TagName;
                t.UserInfo.OTPKey = t.OTPKey;
                t.UserInfo.UserName = t.UserName;
                t.UserInfo.Password = t.Password;
            });
            var list = OTPItemsSource.Select(x => x.UserInfo).ToList();
            File.WriteAllText(UserInfoSavePath, JsonConvert.SerializeObject(list));
        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            var bt = sender as Button;
            var data = bt.DataContext as AuthInfoViewModel;
            OTPItemsSource.Remove(data);
        }

        private void AddNew_Click(object sender, RoutedEventArgs e)
        {
            OTPItemsSource.Add(new AuthInfoViewModel());
        }

        private void OutWebSite_Click(object sender, RoutedEventArgs e)
        {
            Process.Start("https://cloud-kfs.htsc.com.cn/#/");
        }

        private void IutWebSite_Click(object sender, RoutedEventArgs e)
        {
            Process.Start("https://cloud-kfs.htsc.com.cn/#/");
        }


        private void Login_Click(object sender, RoutedEventArgs e)
        {
            var bt = sender as Button;
            var data = bt.DataContext as AuthInfoViewModel;

            OTPItemsSource.Remove(data);
            OTPItemsSource.Insert(0, data);
            var chromeVersionS = chromeVersion.Text;
            try
            {
                //Task.Run(() =>
                //{
                //});
                HuataiCloud.Open(data.UserName, data.Password, () => data.Code, data.Download);
            }
            catch (Exception ex)
            {
            }
        }

        private void Dispose_Click(object sender, RoutedEventArgs e)
        {
            HuataiCloud.Dispose();
        }
    }
}
